<template>
  <Layout style="height: 100%" class="main">
    <Header>
      <div class="logo-v3">
        <img :src="logoTime" @click="checkMenu()" class="logo-image-div"/>
        <img :src="logoImg" class="logo-image-div1"/>
        <div class="user-div-new">
          <Dropdown class="drop-down-v2" :transfer="true" @on-click="clickDropMenu">
            <Row type="flex" justify="end">
              <Col span="20">
                <Row>
                  <div class="name-div">
                        <a href="javascript:void(0)" @click="handleOpen">
                            {{personData.name}}
                            <Icon type="ios-arrow-down"></Icon>
                        </a>
                  </div>
                </Row>
                <Row>
                  <div class="commit-div commit-title">
                    [{{personData.company_name}}]
                  </div>
                </Row>
              </Col>
              <Col span="3" offset="1">
                <Avatar style="background-color: #DB4B00">{{ personData.name }}</Avatar>
              </Col>
            </Row>
            <DropdownMenu slot="list">
              <div class="top-div">
                <div class="index-title3">{{personData.name}}</div>
                <div class="index-title4">[{{personData.company_name}}]</div>
<!--                <div class="level-div index-title5">{{grade_level}}</div>-->
              </div>
              <div class="drop-item-v2" v-for="(item, index) in menuItemList" v-bind:key="index">
                <DropdownItem :name="item.path">
                  <Row class="drop-item-div1">
                    <Col span="3" style="margin-right: 4px;">
                      <img :src="item.url" />
                    </Col>
                    <Col span="16">
                      <div class="index-title3" style="float:left;">{{item.label}}</div>
                    </Col>
                  </Row>
                </DropdownItem>
              </div>
              <div style="float:left;margin-bottom: 5px;margin-top:15px;">
                <div class="back-div index-title2" @click="backTo('/medical/medical-index')">返回主页</div>
                <img :src="tcdlImg" @click="logout()" style="width: 104px;height: 30px;float:left;cursor: pointer;" />
              </div>
            </DropdownMenu>
          </Dropdown>
        </div>
      </div>
    </Header>
    <img id="box" :src="imgUrl" @click="checkMenu()" :class="{'btn1': isCollapsed, 'btn2': !isCollapsed}"/>
    <Layout class="new-menu">
      <Sider class="sider-menu-div" hide-trigger collapsible :collapsed-width="0" :width="220" :style="{background: '#fafafa', paddingTop: '20px'}" style="height: 100%; overflow-y: scroll" v-model="isCollapsed" @on-collapse="aaa">
        <qstb-menu :siderMenus="siderMenuList"></qstb-menu>
      </Sider>
      <Modal v-model="display_model1_obj.modal1" :title="display_model1_obj.text" width="900">
        <div id="printMe">
          <Form label-position="right" :label-width="100">
            <Row>
              <Col span="24" class="ivu-form-item-content" style="text-align: center">
                <embed width="800" v-show="display_model1_obj.modal1" height="600"
                       :src="display_model1_obj.filepath"></embed>
              </Col>
            </Row>
          </Form>
        </div>
        <div slot="footer">
          <Button type="error" size="large" @click="display_model1_obj.modal1=false">关闭</Button>
        </div>
      </Modal>
      <Layout  :style="{overflow: 'hidden',maxHeight: maxH+'px',overflowY:'scroll', paddingTop: '35px', paddingRight: '40px', paddingLeft: '25px', background: '#ffff', paddingBottom: '40px'}">
        <div class="tag-nav-wrapper">
          <new-tag-nav :value="$route" @input="handleClick" :list="tagNavList" @on-close="handleCloseTag"></new-tag-nav>
          <!-- <tags-nav :value="$route" @input="handleClick" :list="tagNavList" @on-close="handleCloseTag"/> -->
        </div>
        <Content :style="{paddingLeft: '0px', paddingTop: '20px', paddingRight: '0px', background: '#ffff'}">
          <keep-alive :include="cacheList">
            <router-view/>
          </keep-alive>
          <!-- <router-view></router-view> -->
        </Content>
      </Layout></Layout>
  </Layout>
</template>

<script>
import './index-copy.less'
import QstbMenu from './qstb-menu'
import logoTime from '@/assets/images/new-grid/index-menu.png'
import logoImg from '@/assets/images/v2-images/系统名称2.png'
import rightImg from '@/assets/images/new-grid/right.png'
import leftImg from '@/assets/images/new-grid/left.png'
import logoutImg from '@/assets/images/new-grid/logout.png'
import passwordImg from '@/assets/images/new-grid/password.png'
import cjwtImg from '@/assets/images/new-grid/常见问题图标.png'
import kfImg from '@/assets/images/new-grid/客服图标.png'
import mmImg from '@/assets/images/new-grid/密码图标.png'
import sbbdImg from '@/assets/images/new-grid/设备绑定图标.png'
import sppxImg from '@/assets/images/new-grid/视频培训图标.png'
import tcdlImg from '@/assets/images/new-grid/退出登录.png'
import xzImg from '@/assets/images/new-grid/下载图标.png'
import { mapMutations, mapActions, mapGetters } from 'vuex'
import { mzMenulist, savelog } from '@/api/eventlist'
import ThreeMenu from './three-menu'
import { clearInterval } from 'timers'
import QRCode from 'qrcodejs2'
import YiqingMenu from '@/view/xian-page/indexv3/yiqing-menu/yiqing-menu'
import TagsNav from '@/components/main/components/tags-nav'
import NewTagNav from '@/components/main/components/new-tag-nav'
import { getNewTagList, routeEqual, getMenuByRouter, localSave, localClear } from '@/libs/util'
import { getRouterReq } from '@/api/routers'
import routers from '@/router/routers'
import MenuList from '@/components/menu-list'
export default {
  name: 'indexv3',
  components: {
    MenuList,
    YiqingMenu,
    ThreeMenu,
    TagsNav,
    QstbMenu,
    NewTagNav
  },
  data () {
    const validatePassCheck = (rule, value, callback) => {
      if (value !== this.passwordInfo.newpassword) {
        callback(new Error('确认密码与新密码不相同'))
      } else {
        callback()
      }
    }
    return {
      siderMenuList: [],
      modalDevice2: false,
      menuItemList: [
        // {
        //   url: kfImg,
        //   label: '客服',
        //   path: 'customer'
        // },
        // {
        //   url: xzImg,
        //   label: '云下载',
        //   path: 'download'
        // },
        // {
        //   url: cjwtImg,
        //   label: '常见问题',
        //   path: 'problem'
        // },
        // {
        //   url: sppxImg,
        //   label: '视频培训',
        //   path: 'video'
        // },
        // {
        //   url: sbbdImg,
        //   label: '设备绑定',
        //   path: 'device'
        // },
        {
          url: mmImg,
          label: '修改密码',
          path: 'setPasword'
        }
      ],
      cjwtImg,
      kfImg,
      mmImg,
      sbbdImg,
      sppxImg,
      tcdlImg,
      xzImg,
      visible: false,
      minZhengMenus: [],
      isCollapsed: true,
      isCollapse: true,
      communityDetail: {
        imgShow: false
      },
      CommunityModal: false,
      upPicData: {
        fileName: 'label',
        filePath: 'grid/label'
      },
      company_grade: '',
      menuName: '',
      device_code: '', // 高拍仪参数
      highMeter1: '', // 高拍仪
      highMeter2: '', // 高拍仪
      highMeter3: '', // 高拍仪
      type: '',
      shuju: [],
      codeUrl: '',
      company_codes: '',
      loginCompanyType: '1', // 登录账号类型 1城市 2农村
      loginNames: '',
      modalDevice: false,
      modalDevice1: false,
      modalDevice3: true,
      disabledCodeBtn: false,
      htmllist: [],
      time: '',
      display_model1_obj1: { modal1: false, filepath: '', html: '' },
      modalDevice2html: '',
      modalQr: false,
      timerInterval: null,
      collapsed: false,
      reloadItem: false,
      logoTime,
      logoImg,
      rightImg,
      leftImg,
      logoutImg,
      passwordImg,
      totalItemNum: 0,
      totalBMNum: 0,
      treeDataList: [],
      searchName: '',
      personData: {},
      routeList: [],
      passwordInfo: { show: false },
      display_model1_obj: { modal1: false, filepath: '' },
      maxH: `${document.documentElement.clientHeight}` - 50,
      btnH: `${document.documentElement.clientHeight}` / 2,
      ruleInline: {
        oldpassword: [
          { required: true, message: '请填写旧密码', trigger: 'blur' }
        ],
        newpassword: [
          { required: true, message: '新密码不能为空', trigger: 'blur' },
          { type: 'string', min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
        ],
        repassword: [
          { required: true, message: '请填写确认密码', trigger: 'blur' },
          { type: 'string', min: 6, message: '密码长度不能少于6位', trigger: 'blur' },
          { validator: validatePassCheck, trigger: 'blur' }
        ]
      },
      yiQingMenus: [],
      adList: [
        // { content: '全科社工们，系统喊你快来试用', ink: 'xx.com' }
      ],
      location_url: '',
      textArr: [],
      number: 0,
      tempTagNavList: [],
      imgUrl: rightImg,
      dataList: [],
      menu_flag: false,
      menu_flag1: false,
      menu_flag2: false,
      menu_flag3: false
    }
  },
  computed: {
    menuitemClasses: function () {
      return [
        'menu-item',
        this.isCollapsed ? 'collapsed-menu' : ''
      ]
    },
    text () {
      return {
        id: this.number,
        val: this.textArr[this.number]
      }
    },
    ...mapGetters([
      'errorCount'
    ]),
    tagNavList () {
      return this.$store.state.app.tagNavList
    },
    tagRouter () {
      return this.$store.state.app.tagRouter
    },
    userAvator () {
      return this.$store.state.user.avatorImgPath
    },
    cacheList () {
      const list = ['ParentView', ...this.tagNavList.length ? this.tagNavList.filter(item => !(item.meta && item.meta.notCache)).map(item => item.name) : []]
      return list
    },
    local () {
      return this.$store.state.app.local
    },
    hasReadErrorPage () {
      return this.$store.state.app.hasReadErrorPage
    },
    unreadCount () {
      return this.$store.state.user.unreadCount
    },
    grade_level () {
      let company_grade = this.$store.state.user.severUserInfo.company_grade
      let grade_level = ''
      switch (company_grade) {
        case '2':
          grade_level = '市级账号'
          break
        case '3':
          grade_level = '区级账号'
          break
        case '4':
          grade_level = '街道账号'
          break
        case '5':
          grade_level = '社区账号'
          break
        default:
      }
      return grade_level
    }
  },
  methods: {
    backTo (name) {
      this.$router.push({
        path: name
      })
    }, // 返回首页
    handleOpen () {
      this.visible = true
    },
    mzMenulist (text) {
      let params = {
        parent_ids: 0
      }
      mzMenulist(this.objToParam(params)).then(ret => {
        if (ret.data.errcode === 0) {
          if (ret.data.data) {
            this.siderMenuList = this.$common.toTree(ret.data.data, 'list', 'id', 'parent_id')
          }
          // this.siderMenuList = ret.data.data;
        }
      })
    },
    objToParam (param) {
      if (Object.prototype.toString.call(param) !== '[object Object]') {
        return ''
      }
      let queryParam = ''
      for (let key in param) {
        if (param.hasOwnProperty(key)) {
          let value = param[key]
          if (queryParam.length === 0) {
            if (!(this.toQueryPair(key, value).length === 0)) {
              queryParam += '?' + this.toQueryPair(key, value)
            }
          } else {
            if (!(this.toQueryPair(key, value).length === 0)) {
              queryParam += '&' + this.toQueryPair(key, value)
            }
          }
        }
      }
      return queryParam
    },
    toQueryPair (key, value) {
      console.log(key, typeof value)
      if (typeof value === 'undefined') {
        // return `&${key}=`
        return ''
      }
      if (value === '' || value === undefined || value === null) {
        return ''
      }
      if (key === 'pageNo' || key === 'pageSize' || key === 'totalRecord') {
        return ''
      }
      return `${key}=${value}`
    },
    clickDropMenu (name) {
      if (name === 'logout') {
        this.logout()
      }
      if (name === 'setPasword') {
        this.$router.push({
          name: 'sysUpdatePassword1'
        })
      }
      switch (name) {
        case 'logout':
          this.logout()
          break
        case 'customer':
          this.modalDevice2 = true
          break
        case 'download':
          this.modalDevice1 = true
          break
        case 'problem':
          this.$router.push({
            name: 'common_problem'
          })
          break
        case 'device':
          this.modalDevice = true
          break
        default:
      }
    },
    aaa (name) {
      console.log(name, '回调')
      if (name === true) {
        setTimeout(() => {
          this.imgUrl = this.rightImg
        }, 200)
      } else if (name === false) {
        setTimeout(() => {
          this.imgUrl = this.leftImg
        }, 200)
      }
    },
    clickMenu (item) {
      console.log(item, '%%%%%%')
      this.$router.push({
        path: item
      })
    },
    checkMenu (flag) {
      this.isCollapsed = !this.isCollapsed
      var box = document.getElementById('box')
      box.hidden = true
      setTimeout(() => {
        box.hidden = false
      }, 200)
      // box.offsetLeft = 180
      // box.remove()
    },
    handleClose (key, keyPath) {
      console.log(key, keyPath)
    },
    hreftwo () {
      this.$router.push({ path: '/message' })
    },
    startMove () {
      // eslint-disable-next-line
        let timer = setTimeout(() => {
        if (this.number === this.textArr.length) {
          this.number = 0
        } else {
          this.number += 1
        }
        this.startMove()
      }, 2500) // 滚动不需要停顿则将2000改成动画持续时间
    },
    ...mapActions([
      'handleLogOut'
    ]),
    getNetworkIp () {
      let needHost = '' // 打开的host
      try {
        // 获得网络接口列表
        let network = os.networkInterfaces()
        for (let dev in network) {
          let iface = network[dev]
          for (let i = 0; i < iface.length; i++) {
            let alias = iface[i]
            if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
              needHost = alias.address
            }
          }
        }
      } catch (e) {
        needHost = 'localhost'
      }
      return needHost
    },
    logout () {
      this.handleLogOut().then(() => {
        clearInterval(this.timerInterval)
        localClear()
        if (location.href.indexOf('qstb.mzj.shenyang.gov.cn') !== -1) {
          window.open('http://qstb.mzj.shenyang.gov.cn/#/login')
        } else { // 生产环境
          this.$router.push({ name: 'login' })
        }
      })
    },
    viewProcess (item) {
      if (item.file_url) {
        this.display_model1_obj.text = item.type_name
        this.display_model1_obj.modal1 = true
        this.display_model1_obj.filepath = item.file_url
      } else {
        this.$Notice.error({ title: '无文件', desc: '当前事项无PDF说明文档' })
      }
    },
    openPage (e) {
      console.log('!!!', e)
      // console.log('!!!!!', e)
      if (e) {
        let a = e.split('=')
        this.menuName = a[0]
        this.$router.push({ path: a[1] })
      } else {
        this.$Notice.error({ title: '无文件', desc: '等待添加路径' })
      }
    },
    getCode (codeUrl) {
      var qrcode = new QRCode(document.getElementById('qrcode'), {
        text: codeUrl,
        top: 200,
        width: 300,
        height: 300,
        colorDark: '#000000',
        colorLight: '#ffffff',
        correctLevel: QRCode.CorrectLevel.H
      })
      return qrcode
    },
    ...mapMutations([
      'setBreadCrumb',
      'setTagNavList',
      'addTag',
      'setLocal',
      'setFirstMenuId',
      'setHomeRoute',
      'closeTag'
    ]),
    ...mapActions([
      'handleLogin',
      'getUnreadMessageCount',
      'getAjaxRouterData'
    ]),
    turnToPage (route) {
      // console.log(route, 'main/turnToPage')
      let { name, params, query } = {}
      if (typeof route === 'string') name = route
      else {
        name = route.name
        params = route.params
        query = route.query
      }
      if (name.indexOf('isTurnByHref_') > -1) {
        window.open(name.split('_')[1])
        return
      }
      this.$router.push({
        name,
        params,
        query
      })
    },
    handleCollapsedChange (state) {
      this.collapsed = state
    },
    handleCloseTag (res, type, route) {
      if (type !== 'others') {
        if (type === 'all') {
          this.turnToPage(this.$config.homeName)
        } else {
          if (routeEqual(this.$route, route)) {
            this.closeTag(route)
          }
        }
      }
      this.setTagNavList(res)
    },
    handleClick (item) {
      // console.log(item, '执行main/handleClick')
      this.turnToPage(item)
    },
    getRouterListData () {
      getRouterReq('222').then(res => {
        let listData = getMenuByRouter(res.data, 'admin')
        this.menuList001 = listData
      })
    },
    groupMenuSelect (id, menusData) {
      // this.setFirstMenuId(id)
      localSave('first-menus-data', JSON.stringify(menusData))
      this.$store.dispatch('getAjaxRouterData', id)
    },
    savelogea () {
      let params = {
        index_id: this.display_model1_obj1.index_id
      }
      savelog(params).then(res => {})
      this.display_model1_obj1.modal1 = false
      setTimeout(() => {
        this.opennoticeDocument()
      }, 500)
    }
  },
  watch: {
    '$route' (newRoute) {
      console.log(newRoute, '第二是监听watch新的路由变化')
      let tempMenuList = this.menuList
      console.log(this.menuList, '获取当菜单数据')
      for (let key in tempMenuList) {
        let childData = tempMenuList[key].children
        if (tempMenuList[key].name && tempMenuList[key].name === newRoute.name) {
          console.log('ok11')
          newRoute.meta.title = tempMenuList[key].meta.title // 为了不在路由里面取名字写的循环
        } else {
          if (tempMenuList[key].children && tempMenuList[key].children.length > 0) {
            for (let k2 in childData) {
              let chid = childData[k2]
              if (chid.name === newRoute.name) {
                console.log('ok')
                newRoute.meta.title = chid.meta.title // 为了不在路由里面取名字写的循环
              }
            }
          }
        }
      }
      const { name, query, params, meta } = newRoute
      if (newRoute.meta.hide === true) {
        this.addTag({
          route: { name, query, params, meta },
          type: 'push'
        })
        this.setBreadCrumb(newRoute)
        this.tempTagNavList = []
        for (var i = 0; i < this.tagNavList.length; i++) {
          if (this.tagNavList[i].meta.hide === true) {
            this.tempTagNavList.push(this.tagNavList[i])
          }
        }
        this.setTagNavList(getNewTagList(this.tempTagNavList, newRoute))
      }
    }
  },
  mounted () {
    console.log(this.grade_level, '登记')
    this.startMove()
    this.location_url = window.location.href
    this.mzMenulist()
    this.setTagNavList()
    this.setHomeRoute(routers)
    const { name, params, query, meta } = this.$route
    this.addTag({
      route: { name, params, query, meta }
    })
    let severUserInfo = this.$store.state.user.severUserInfo
    this.company_grade = severUserInfo.company_grade
    this.loginCompanyType = severUserInfo.company_type
    this.device_code = severUserInfo.email
    this.company_codes = severUserInfo.company_code
    this.loginNames = severUserInfo.loginName
    this.personData.name = severUserInfo.name
    this.personData.company_name = severUserInfo.company_name
    this.highMeter1 = severUserInfo.email
    this.routeList = this.$store.state.app.mainv3Nav
  }
}
</script>
<style lang="less" scoped>
  .new-menu .ivu-menu-light.ivu-menu-vertical .ivu-menu-item-active:not(.ivu-menu-submenu) {
    color: #B40001;
    background: white;
    z-index: 2;
    height: 45px;
    border-radius: 5px;
    background: #efefef;
    margin-left: 10px;
    margin-right: 10px;
    padding-left: 10px;
    padding-right: 0px;
  }
  .new-menu .ivu-menu-item:hover {
      //color: #B40001;
      font-weight: bold;
  }
  .new-menu /deep/ .ivu-menu-vertical .ivu-menu-submenu-title:hover {
    //color: #B40001;
  }
  .new-menu /deep/ .ivu-menu-vertical.ivu-menu-light:after {
    content: '';
    display: block;
    width: 0px;
    height: 100%;
    background: #dcdee2;
    position: absolute;
    top: 0;
    bottom: 0;
    right: 0;
    z-index: 1;
  }
  .ivu-select-dropdown {
    padding: 5px 0 10px 0;
  }
  .ivu-dropdown-menu {
    min-width: 100px;
    width: 238px;
    padding: 5px 10px;
  }
  /deep/ .ivu-modal-header {
    border-bottom: 0px solid #e8eaec;
    padding: 30px 30px 0px 30px;
    line-height: 1;
  }
  /deep/ .ivu-modal-header-inner {
    font-family: "PingFang SC Bold";
    font-weight: 700;
    font-size: 14px;
    text-align: left;
    color: #b40001;
  }
  /deep/ .ivu-modal-footer {
    border-top: 0px solid #e8eaec;
    padding: 0px 30px 30px 30px;
    text-align: left;
  }
  /deep/ .ivu-modal-close {
    border-radius: 10px;
    background-color: #f6f4f4;
    right: 30px;
    top: 30px;
    width: 20px;
    height: 20px;
  }
  /deep/ .ivu-modal-close .ivu-icon-ios-close {
    font-size: 20px;
    top: 0px;
  }
  /deep/ .ivu-modal-body {
    padding: 14px 30px 5px 30px;
  }
  /deep/ .ivu-input {
    border: 1px solid #dcdee2;
    box-shadow: none;
  }
  /deep/ .ivu-input:hover {
    border: 1px solid #dcdee2;
    box-shadow: none;
  }
  /* 隐藏滑动条 */
  .sider-menu-div::-webkit-scrollbar {
    display: none;
  }
  /* 隐藏滑动条 */
</style>
